package cn.com.franke.basic;

import com.google.common.base.Optional;
import org.junit.Test;

import java.util.Set;

/**
 * Created by liuxianzhao on 2017/4/26.
 */
public class OptionalTest {

    @Test
    public void test1() throws Exception {
        Optional<Integer> possible = Optional.of(6);
        if (possible.isPresent()) {
            System.out.println("possible isPresent:" + possible.isPresent());
            System.out.println("possible value:" + possible.get());
        }
    }

    @Test
    public void test2() {
        Optional<Integer> possible = Optional.of(6);
        Optional<Integer> absentOpt = Optional.absent();
        Optional<Integer> NullableOpt = Optional.fromNullable(null);
        Optional<Integer> NoNullableOpt = Optional.fromNullable(10);
        if (possible.isPresent()) {
            System.out.println("possible isPresent:" + possible.isPresent());
            System.out.println("possible value:" + possible.get());
        }
        if (absentOpt.isPresent()) {
            System.out.println("absentOpt isPresent:" + absentOpt.isPresent());
            ;
        }
        if (NullableOpt.isPresent()) {
            System.out.println("fromNullableOpt isPresent:" + NullableOpt.isPresent());
            ;
        }
        if (NoNullableOpt.isPresent()) {
            System.out.println("NoNullableOpt isPresent:" + NoNullableOpt.isPresent());
            ;
        }
    }

    @Test
    public void test3() {
        Optional<Long> value = Optional.fromNullable(null);
        if (value.isPresent() == true) {
            System.out.println("获得返回值: " + value.get());
        } else {
            System.out.println("获得返回值: " + value.or(-12L));
        }
        System.out.println("获得返回值 orNull: " + value.orNull());

        Optional<Long> valueNoNull = Optional.fromNullable(15L);
        if (valueNoNull.isPresent() == true) {
            Set<Long> set = valueNoNull.asSet();
            System.out.println("获得返回值 set 的 size : " + set.size());
            System.out.println("获得返回值: " + valueNoNull.get());
        } else {
            System.out.println("获得返回值: " + valueNoNull.or(-12L));
        }

        System.out.println("获得返回值 orNull: " + valueNoNull.orNull());
    }
    @Test
    public void test4() {
        Optional<String> value = Optional.fromNullable("");
        if (value.isPresent() == true) {
            System.out.println("获得返回值: " + value.get());
        } else {
            System.out.println("获得返回值: " + value.or(""));
        }
        System.out.println("获得返回值 orNull: " + value.orNull());
    }

}
